package cug.hexy.springbatchrabbitmqdemo.listener;

import cug.hexy.springbatchrabbitmqdemo.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TaskListener {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job simpleJob;

    @RabbitListener(queues = RabbitMQConfig.TASK_QUEUE)
    public void receive(String taskId) {
        try {
            System.out.println("收到任务：" + taskId);
            JobParameters params = new JobParametersBuilder()
                    .addString("taskId", taskId)
                    .addLong("timestamp", System.currentTimeMillis())
                    .toJobParameters();
            jobLauncher.run(simpleJob, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
